package cn.dfusion.back.service;

import cn.dfusion.blockchain.BlockChainException;
import cn.dfusion.blockchain.PropertiesConfigurator;
import cn.dfusion.blockchain.entity.Message;
import cn.dfusion.blockchain.entity.RecordInfo;
import cn.dfusion.blockchain.entity.TransactionInfo;
import cn.dfusion.blockchain.repo.BlockChainClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author ipenta
 * @ClassName: VaccineService
 * @Description: TODO
 * @date 2017-09-25 上午10:24
 */
@Service
public class VaccineService {

	private static final Logger logger = LoggerFactory.getLogger(VaccineService.class);

	private static final String CIRCULATIONS = "circulations";
	private static final String INOCULATIONS = "inoculationz";
	private static final String VACCINE_ID = "VACCINE_ID";

	@Autowired
	BlockChainClient blockChainClient;

	@Autowired
	private PropertiesConfigurator propertiesConfigurator;

	/**
	 *查询记录
	 *
	 * */
	public List<TreeMap<String,Object>> findRecord(String vaccineId) {
		List<TreeMap<String,Object>> treeMapList = new ArrayList<>();

		Map<String,String> filter = new HashMap<>();
		filter.put(VACCINE_ID,vaccineId);
		List<TransactionInfo> inoculations = messageConverter(blockChainClient.lookupTxByKey(INOCULATIONS, filter));
		List<TransactionInfo> circulations = messageConverter(blockChainClient.lookupTxByKey(CIRCULATIONS, filter));
		for (TransactionInfo transactionInfo: circulations){
			RecordInfo recordInfo =  transactionInfo.getContentInfo();
			treeMapList.add(recordInfo.getRecordContent());
		}
		for (TransactionInfo transactionInfo: inoculations){
			RecordInfo recordInfo =  transactionInfo.getContentInfo();
			treeMapList.add(recordInfo.getRecordContent());
		}

		return treeMapList;
	}




	// 数据转换
	private <T> T messageConverter(Message<T> message) {
		if (message.getStatus().equals(Message.Status.SUCCESS.getValue())) {
			return message.getData();
		} else {
			throw new BlockChainException(message.getErrorContent());
		}
	}



}

